<?php /** @noinspection ALL */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/5/25 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\controllers;

use Yii;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;

/**
 * 基础 接口 无需权限
 * @package api\controllers
 */
class BaseController extends Controller
{
    public function behaviors()
    {
        $behaviors = ArrayHelper::merge([
            'corsFilter' => [
                'class' => Cors::class,
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Methods' => ['*'],
                    'Access-Control-Request-Headers' => ['*']
                ]
            ]
        ], parent::behaviors());
        // HTTP 头发送目前的速率限制信息
        $behaviors['rateLimiter']['enableRateLimitHeaders'] = false;
        return $behaviors;
    }

    /**
     * 检测会员登录状态
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        // 检测会员登录状态
        if (Yii::$app->getUser()->isGuest) {
            $auth = new HttpBearerAuth();
            $authHeader = Yii::$app->getRequest()->getHeaders()->get($auth->header);
            if ($auth->pattern !== null) {
                if (preg_match($auth->pattern, $authHeader, $matches)) {
                    $authHeader = $matches[1];
                    Yii::$app->getUser()->loginByAccessToken($authHeader, get_class($auth));
                }
            }
        }
        return parent::beforeAction($action);
    }

    public function actions()
    {
        $config = Yii::$app->config->getSiteItem('imgCaptcha');
        $len = Yii::$app->config->getSiteItem('imgCaptchaLength');
        $len = $len <= 8 && $len >= 4 ? $len : 6;
        $color = trim($config['foreColor'], '#');
        $foreColorIsRandom = $color == 'auto' ? true : false;
        $foreColor = $color == 'auto' ? 0x2040A0 : intval('0x' . strtoupper($color), 16);
        return [
            // 本地验证码
            'captcha' => [
                'class' => 'common\actions\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'minLength' => (int) $len,
                'maxLength' => (int) $len,
                'width' => (int) $config['width'],
                'padding' => (int) $config['padding'],
                'offset' => (int) $config['offset'],
                'foreColor' => $foreColor,
                'imageLibrary' => trim($config['imageLibrary']) == 'imagick' ? 'imagick' : 'gd',
                'foreColorIsRandom' => (boolean) $foreColorIsRandom, //验证码颜色随机
                'isWriteNoise' => (boolean) $config['isWriteNoise'],
                'isWriteCurve' => (boolean) $config['isWriteCurve'],
                'captchaCacheDuration' => (int) $config['cacheDuration'],
                'noiseMinFontSize' => (int) $config['noiseMinFontSize'],
                'noiseMaxFontSize' => (int) $config['noiseMaxFontSize'],
                'minFontSize' => (int) $config['minFontSize'],
                'maxFontSize' => (int) $config['maxFontSize'],
                'disturbCharCount' => (int) $config['disturbCharCount'],
            ]
        ];
    }

    /**
     * 检测post请求
     * 如果非post请求，发送4405代码
     * @return mixed
     */
    public function validateIsPost()
    {
        if (!Yii::$app->getRequest()->getIsPost()) {
            $response = Yii::$app->getResponse();
            $response->data = Yii::$app->api->send(4405);
            $response->send();
        }
        return true;
    }
}
